package com.chinawlx.wlxteacher.ui.activity;

import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chinawlx.wlxteacher.R;
import com.chinawlx.wlxteacher.network.WLXHttpRxHelper;
import com.chinawlx.wlxteacher.network.bean.WLXCommentListBean;
import com.chinawlx.wlxteacher.ui.adapter.WLXCommentListAdapter;
import com.chinawlx.wlxteacher.ui.fragment.WLXLoadingFragment;
import com.chinawlx.wlxteacher.utils.WLXConstant;
import com.chinawlx.wlxteacher.utils.WLXDateUtil;
import com.chinawlx.wlxteacher.utils.WLXGreenDaoUtil;
import com.chinawlx.wlxteacher.utils.WLXLogUtil;
import com.chinawlx.wlxteacher.utils.WLXNetUtil;
import com.chinawlx.wlxteacher.widget.WLXCustomToast;
import com.chinawlx.wlxteacher.wlx_homework;
import com.chinawlx.wlxteacher.wlx_homeworkDao;
import com.chinawlx.wlxteacher.wlx_homework_comment;
import com.chinawlx.wlxteacher.wlx_homework_commentDao;
import com.google.gson.Gson;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bingoogolapple.refreshlayout.BGAMeiTuanRefreshViewHolder;
import cn.bingoogolapple.refreshlayout.BGARefreshLayout;
import rx.Subscriber;

/**
 * 回复列表界面
 * 思路:
 * 1.首先拉取数据,服务器没有做分页,一次全部数据
 * 2.全部插入数据库
 * 3.
 */
public class WLXCommentListActivity extends WLXBaseActivity implements BGARefreshLayout
        .BGARefreshLayoutDelegate {

    @BindView(R.id.iv_back)
    ImageView mIvBack;
    @BindView(R.id.lv_comment_list)
    ListView mLvCommentList;
    @BindView(R.id.tv_msg)
    TextView mTVMsg;
    @BindView(R.id.rl_container_empty)
    RelativeLayout mRlContainerEmpty;//空白区域

    public static final String LOADING_TAG = "WLXCommentListActivity";


    private boolean mHasMoreData = true;//是否还有上拉数据
    private boolean mIsPullToRefresh = true;//是否是下拉刷新

    private int paging_index = 1;//分页索引（1:表示第一页）
    private int paging_size = 10;//每页大小（默认10条）
    private WLXCommentListAdapter mCommentListAdapter;
    private WLXLoadingFragment mLoadingFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wlxcomment_list);
        ButterKnife.bind(this);
        mLoadingFragment = WLXLoadingFragment.getInstance();
        init();
        mRefreshLayout.beginRefreshing();
    }

    private void init() {
        initRefreshLayout();
        initView();
    }

    private void initView() {
        mCommentListAdapter = new WLXCommentListAdapter(this);
        mLvCommentList.setAdapter(mCommentListAdapter);
    }

    //初始化数据
    private void initData() {
        WLXHttpRxHelper.getInstance().getCommentList(WLXConstant.GRADE_ID + "", new Subscriber
                <WLXCommentListBean>() {

            @Override
            public void onCompleted() {
                loadDataFromDb();
            }

            @Override
            public void onError(Throwable e) {
                onCompleted();
            }

            @Override
            public void onNext(WLXCommentListBean bean) {
                if (bean.getCode() == 0) {
                    insertData2Db(bean);
                } else {
                    WLXCustomToast.show("数据获取异常");
                }

            }
        });
    }

    //数据加载完成,展示数据库数据
    private void loadDataFromDb() {
        LoadDataFromDbTask task = new LoadDataFromDbTask();
        task.execute("");
    }

    //上拉加载更多不是异步就无法显示加载提示
    class LoadDataFromDbTask extends AsyncTask<String, Integer, List<wlx_homework>> {

        @Override
        protected List<wlx_homework> doInBackground(String... params) {

            List<wlx_homework> wlx_homeworks = WLXGreenDaoUtil.getHomeWorkDao().queryBuilder
                    ().where
                    (wlx_homeworkDao.Properties.Grade_id.eq(WLXConstant.GRADE_ID),
                            wlx_homeworkDao
                                    .Properties.Is_teacher_comment.eq(1),
                            wlx_homeworkDao.Properties.Is_family_reply.eq(1)
                            , wlx_homeworkDao.Properties.Is_replied.eq(0)).orderDesc
                    (wlx_homeworkDao
                            .Properties.Creation_date)
                    .offset((paging_index - 1) * paging_size).limit(paging_size).list();
            mHasMoreData = wlx_homeworks.size() == paging_size;
            return wlx_homeworks;
        }

        @Override
        protected void onPostExecute(List<wlx_homework> wlx_homeworks) {
            if (wlx_homeworks.size() == 0) {
                mRefreshLayout.setVisibility(View.GONE);
                mRlContainerEmpty.setVisibility(View.VISIBLE);
                mTVMsg.setText("无数据");
            } else {
                if (mIsPullToRefresh) {
                    mRefreshLayout.endRefreshing();
                    mCommentListAdapter.setData(wlx_homeworks);
                } else {
                    mRefreshLayout.endLoadingMore();
                    mCommentListAdapter.addData(wlx_homeworks);
                }
            }
            mLoadingFragment.dismiss();
            mRefreshLayout.endRefreshing();
            mRefreshLayout.endLoadingMore();
        }
    }

    //返回的数据项存入wlx_homework里，请注意每个数据项里的CommentList数据请存入wlx_homework_comment
    private void insertData2Db(WLXCommentListBean bean) {
        //homework表数据
        List<WLXCommentListBean.DataBean.HomeworkListBean> homework_list = bean.getData()
                .getHomework_list();
        for (WLXCommentListBean.DataBean.HomeworkListBean homeworkList : homework_list) {
            String homework_id = Integer.toString(homeworkList.getId());
            WLXConstant.HOMEWORK_ID = homework_id;
            int teacher_user_id = homeworkList.getTeacher_user_id();
            int family_user_id = homeworkList.getFamily_user_id();
            int student_id = homeworkList.getStudent_id();
            int grade_id = homeworkList.getGrade_id();
            int schedule_id = homeworkList.getSchedule_id();
            String content = homeworkList.getContent();
            String homework_content_code = homeworkList
                    .getHomework_content().getKey();
            String status_code = homeworkList.getStatus().getKey();
            if ("deleted".equals(status_code)) continue;//被删除的消息不处理

            int is_teacher_comment = homeworkList.isIs_teacher_comment() ?
                    1 : 0;
            int is_family_reply = homeworkList.isIs_family_reply() ? 1 : 0;
            int is_replied = homeworkList.isIs_replied() ? 1 : 0;
            String extend_info = new Gson().toJson(homeworkList.getExtend());
            long last_modified_date = WLXDateUtil.getStringToDate(homeworkList
                    .getLast_modified_date());
            long creation_date = WLXDateUtil.getStringToDate(homeworkList
                    .getCreation_date());
            //插入作业数据
            wlx_homework wlxHomeWork = new wlx_homework(homework_id,
                    teacher_user_id,
                    family_user_id,
                    student_id, grade_id,
                    schedule_id, content, homework_content_code, status_code,
                    is_teacher_comment, is_family_reply, is_replied, extend_info,
                    last_modified_date, creation_date);
            //1,查询homework_id这条记录,homework_id是唯一的
            List<wlx_homework> wlx_homeworks = WLXGreenDaoUtil.getHomeWorkDao()
                    .queryBuilder()
                    .where(wlx_homeworkDao
                            .Properties.Homework_id.eq(WLXConstant.HOMEWORK_ID))
                    .list();
            if (wlx_homeworks.size() > 0) {
                WLXLogUtil.printE("homework_id查询到的指定id记录信息:" + homeworkList
                        .toString());
                //2, 有这条记录, 就去对比last_modified_date, 如果服务器时间更新, 就update表数据
                if (last_modified_date > wlx_homeworks.get(0)
                        .getLast_modified_date()) {
                    WLXGreenDaoUtil.getHomeWorkDao().update(wlxHomeWork);
                }
            } else {
                //无数据,就直接插入数据
                WLXGreenDaoUtil.getHomeWorkDao().insert(wlxHomeWork);
            }

            //评论数据,wlx_homework_comment表
            List<WLXCommentListBean.DataBean.HomeworkListBean.CommentListBean> comment_list =
                    homeworkList.getComment_list();
            for (WLXCommentListBean.DataBean.HomeworkListBean.CommentListBean homeworkcomment :
                    comment_list) {
                String homework_comment_id = Integer.toString(homeworkcomment.getId());
                WLXConstant.HOMEWORK_COMMENT_ID = homework_comment_id;
                int homework_id2 = homeworkcomment.getHomework_id();
                int user_id = homeworkcomment.getUser_id();
                content = homeworkcomment.getContent();
                int is_teacher = homeworkcomment.isIs_teacher() ? 1 : 0;
                extend_info = new Gson().toJson(homeworkcomment.getExtend());
                String comment_content_code = homeworkcomment.getComment_content_code
                        ().getKey();
                creation_date = WLXDateUtil.getStringToDate(homeworkcomment
                        .getCreation_date());
                last_modified_date = WLXDateUtil.getStringToDate(homeworkcomment
                        .getLast_modified_date());
                //插入作业评论数据
                wlx_homework_comment wlxHomeWorkComment = new wlx_homework_comment
                        (homework_comment_id, homework_id2, user_id,
                                content,
                                is_teacher, extend_info,
                                comment_content_code, creation_date,
                                last_modified_date);
                //1,查询homework_comment_id这条记录,homework_comment_id是唯一的
                List<wlx_homework_comment> wlx_homework_comments = WLXGreenDaoUtil
                        .getHomeWorCommentkDao()
                        .queryBuilder()
                        .where(wlx_homework_commentDao
                                .Properties.Homework_comment_id.eq(WLXConstant
                                        .HOMEWORK_COMMENT_ID)).list();
                if (wlx_homework_comments.size() > 0) {
                    //2, 有这条记录, 就去对比last_modified_date, 如果服务器时间更新, 就update表数据
                    if (last_modified_date > wlx_homework_comments.get(0)
                            .getLast_modified_date()) {
                        WLXGreenDaoUtil.getHomeWorCommentkDao().update
                                (wlxHomeWorkComment);
                    }
                } else {
                    //无数据,就直接插入数据
                    WLXGreenDaoUtil.getHomeWorCommentkDao().insert(wlxHomeWorkComment);
                }
            }
        }

    }

    @OnClick(R.id.iv_back)
    public void onClick() {
        finish();
    }

    //--------刷新内容---------
    private BGARefreshLayout mRefreshLayout;

    private void initRefreshLayout() {
        mRefreshLayout = (BGARefreshLayout) findViewById(R.id.rl_modulename_refresh);
        mRefreshLayout.setDelegate(this);
        BGAMeiTuanRefreshViewHolder meiTuanRefreshViewHolder = new BGAMeiTuanRefreshViewHolder
                (this, true);
        meiTuanRefreshViewHolder.setPullDownImageResource(R.drawable.yuanq);
        meiTuanRefreshViewHolder.setChangeToReleaseRefreshAnimResId(R.drawable
                .bga_refresh_mt_change_to_release_refresh);
        meiTuanRefreshViewHolder.setRefreshingAnimResId(R.drawable.bga_refresh_mt_refreshing);

        mRefreshLayout.setRefreshViewHolder(meiTuanRefreshViewHolder);
    }

    //开始刷新
    @Override
    public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
        if (WLXNetUtil.netIsAvailable()) {
            mIsPullToRefresh = true;
            paging_index = 1;
            mLoadingFragment.show(getSupportFragmentManager(),LOADING_TAG);
            initData();
        } else {
            WLXCustomToast.show("无网络");
            loadDataFromDb();
        }
    }

    //处理上拉加载,在这里上拉加载更多,
    @Override
    public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
        if (mHasMoreData) {
            mIsPullToRefresh = false;
            paging_index++;
            mLoadingFragment.show(getSupportFragmentManager(),LOADING_TAG);
            loadDataFromDb();
            return true;
        } else {
            WLXCustomToast.show("没有更多数据");
            return false;
        }
    }

}
